<template>
  <div id="tags-view-container" class="tags-view-container">
    <scroll-pane ref="scrollPane" class="tags-view-wrapper" @scroll="handleScroll">
      <router-link
        v-for="tag in visitedViews"
        ref="tag"
        :key="tag.path"
        :class="isActive(tag) ? 'active' : ''"
        :to="{ path: tag.path }"
        tag="span"
        class="tags-view-item"
        @click.middle="!isAffix(tag) ? closeSelectedTag(tag) : ''"
        @contextmenu.prevent="openMenu(tag, $event)"
      >
        {{ tag.title }}
        <span v-if="!isAffix(tag)" class="el-icon-close" @click.prevent.stop="closeSelectedTag(tag)" />
      </router-link>
    </scroll-pane>
    <ul v-show="visible" :style="{ left: left + 'px', top: top + 'px' }" class="contextmenu">
      <li @click="refreshSelectedTag(selectedTag)">刷新</li>
      <li v-if="!isAffix(selectedTag)" @click="closeSelectedTag(selectedTag)">关闭</li>
      <li @click="closeOthersTags">关闭其他</li>
      <li @click="closeAllTags(selectedTag)">关闭所有</li>
    </ul>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, nextTick, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useAppStore } from '@/stores/app'
import ScrollPane from './ScrollPane.vue'
import type { TabItem } from '@/types/system'

const route = useRoute()
const router = useRouter()
const appStore = useAppStore()

// 响应式数据
const visible = ref(false)
const top = ref(0)
const left = ref(0)
const selectedTag = ref<TabItem>({} as TabItem)
const affixTags = ref<TabItem[]>([])

// 计算属性
const visitedViews = computed(() => appStore.tabs)

// 是否激活
const isActive = (tag: TabItem) => {
  return tag.path === route.path
}

// 是否固定标签
const isAffix = (tag: TabItem) => {
  return tag.affix
}

// 添加标签
const addTags = () => {
  const { name } = route
  if (name && route.path !== '/login') {
    appStore.addTab({
      title: (route.meta?.title as string) || '未命名',
      name: name as string,
      path: route.path,
      closable: !route.meta?.affix,
      affix: !!route.meta?.affix
    })
  }
}

// 关闭选中的标签
const closeSelectedTag = (view: TabItem) => {
  appStore.removeTab(view.path)
  if (isActive(view)) {
    toLastView(appStore.tabs, view)
  }
}

// 关闭其他标签
const closeOthersTags = () => {
  router.push(selectedTag.value.path)
  appStore.removeOtherTabs(selectedTag.value.path)
}

// 关闭所有标签
const closeAllTags = (view: TabItem) => {
  appStore.removeAllTabs()
  if (affixTags.value.some(tag => tag.path === view.path)) {
    return
  }
  toLastView(appStore.tabs, view)
}

// 跳转到最后一个标签
const toLastView = (visitedViews: TabItem[], view: TabItem) => {
  const latestView = visitedViews.slice(-1)[0]
  if (latestView) {
    router.push(latestView.path)
  } else {
    if (view.name === 'Dashboard') {
      router.replace({ path: '/redirect' + view.path })
    } else {
      router.push('/')
    }
  }
}

// 刷新选中的标签
const refreshSelectedTag = (view: TabItem) => {
  appStore.removeCachedView(view.name)
  nextTick(() => {
    router.replace({
      path: '/redirect' + view.path
    })
  })
}

// 打开右键菜单
const openMenu = (tag: TabItem, e: MouseEvent) => {
  const menuMinWidth = 105
  const offsetLeft = 15
  const offsetWidth = 15
  const maxLeft = offsetLeft + offsetWidth - menuMinWidth
  let menuLeft = e.clientX + offsetLeft

  if (menuLeft > maxLeft) {
    menuLeft = maxLeft
  }

  top.value = e.clientY
  left.value = menuLeft
  visible.value = true
  selectedTag.value = tag
}

// 关闭右键菜单
const closeMenu = () => {
  visible.value = false
}

// 处理滚动
const handleScroll = () => {
  closeMenu()
}

// 监听路由变化
watch(route, () => {
  addTags()
})

// 监听右键菜单
watch(visible, (value) => {
  if (value) {
    document.body.addEventListener('click', closeMenu)
  } else {
    document.body.removeEventListener('click', closeMenu)
  }
})

// 生命周期
onMounted(() => {
  addTags()
})

onUnmounted(() => {
  document.body.removeEventListener('click', closeMenu)
})
</script>

<style lang="scss" scoped></style>

<style lang="scss">
// TagsView 样式（全局）
.tags-view-container {
  background: var(--el-bg-color);
  border-bottom: 1px solid var(--el-border-color-lighter);
  padding: 8px 8px;
}

// 滚动容器样式（来自 ScrollPane 根元素）
.scroll-container.tags-view-wrapper {
  height: 40px;
  display: flex;
  align-items: center;
  overflow: hidden;
}

.scroll-container.tags-view-wrapper .scroll-wrapper {
  display: inline-flex;
  align-items: center;
}

// 单个标签样式
.tags-view-item {
  display: inline-flex;
  align-items: center;
  height: 26px;
  padding: 0 8px;
  margin-right: 6px;
  font-size: 12px;
  line-height: 1;
  color: var(--el-text-color-regular);
  background: var(--el-fill-color-lighter);
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 6px;
  text-decoration: none;
  transition: all 0.2s ease;

  &:hover {
    background: var(--el-fill-color-light);
  }

  &.active,
  &.router-link-active.active {
    color: var(--el-color-primary);
    background: var(--el-color-primary-light-9);
    border-color: var(--el-color-primary);
    font-weight: 500;
  }

  // 关闭图标（用伪元素渲染 ×）
  .el-icon-close {
    width: 16px;
    height: 16px;
    margin-left: 6px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    border-radius: 4px;
    color: var(--el-text-color-secondary);
    transition: background-color 0.2s ease, color 0.2s ease;

    &::before {
      content: '×';
      font-size: 12px;
      line-height: 1;
      font-weight: 600;
    }

    &:hover {
      background: var(--el-fill-color-dark);
      color: var(--el-text-color-regular);
    }
  }

  &.active .el-icon-close {
    color: var(--el-color-primary);
  }
}

// 右键菜单样式（保持原样可按需微调）
.contextmenu {
  position: fixed;
  z-index: 3000;
  background: var(--el-bg-color-overlay);
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 6px;
  box-shadow: 0 8px 24px rgba(0,0,0,0.08);
  padding: 6px 0;
  list-style: none;
  min-width: 120px;

  li {
    padding: 8px 12px;
    font-size: 12px;
    color: var(--el-text-color-regular);
    cursor: pointer;

    &:hover {
      background: var(--el-fill-color-light);
      color: var(--el-text-color-primary);
    }
  }
}
</style>
